use crate::utils::db_util::get_global_db_util;
use crate::utils::ajax_result::AjaxResult;
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ShelfStatistics {
    pub total_count: i64,
    pub on_shelf_count: i64,
    pub rented_count: i64,
}

pub async fn get_shelf_statistics() -> AjaxResult<ShelfStatistics> {
    let db_util = get_global_db_util();
    
    // 使用一条SQL查询所有统计数据
    let sql = r#"
        SELECT 
            COUNT(*) as total_count,
            COUNT(CASE WHEN zhw_zt = '0' OR zz_zt = '1' THEN 1 END) as on_shelf_count,
            COUNT(CASE WHEN zhw_zt = '1' OR zz_zt = '2' THEN 1 END) as rented_count
        FROM account_info
    "#;
    
    let result = db_util.raw_query(sql, vec![]).await;
    
    match result {
        Ok(rows) => {
            if !rows.is_empty() {
                let row = &rows[0];
                let statistics = ShelfStatistics {
                    total_count: row["total_count"].as_i64().unwrap_or(0),
                    on_shelf_count: row["on_shelf_count"].as_i64().unwrap_or(0),
                    rented_count: row["rented_count"].as_i64().unwrap_or(0),
                };
                AjaxResult::succeed(statistics)
            } else {
                AjaxResult::succeed(ShelfStatistics::default())
            }
        }
        Err(e) => {
            log::error!("获取货架统计数据失败: {:?}", e);
            AjaxResult::internal_error("获取货架统计数据失败")
        }
    }
}